//
//  ASLoadPracUnitCodeVC.m
//  AttendenceSys
//
//  Created by 窦芳俊 on 2017/4/6.
//  Copyright © 2017年 窦芳俊. All rights reserved.
//

#import "ASLoadPracUnitCodeVC.h"

@interface ASLoadPracUnitCodeVC ()

@property (nonatomic, assign) NSInteger codeType;
@property (nonatomic, strong) NSString *pracUnitId;
@property (nonatomic, strong) UIImageView *imageView;

@end


@implementation ASLoadPracUnitCodeVC

- (instancetype)initWithCodeType:(NSInteger)type unitId:(NSString *)unitId
{
    self = [super init];
    if (self)
    {
        _codeType = type;
        _pracUnitId = unitId;
    }
    
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self initView];
    
    [self loadCodeUrl];
    
    self.strNavTitle = ((_codeType == 1) ? @"进场" : @"离场");
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

- (void)initView
{
    UIImageView* bgView = [[UIImageView alloc] initWithFrame:CGRectMake(0,
                                                                        0,
                                                                        self.view.frame.size.width,
                                                                        self.view.frame.size.height)];
    bgView.backgroundColor = [UIColor whiteColor];
    //bgView.image = [UIImage imageNamed:@"bg_personal"];
    bgView.userInteractionEnabled = YES;
    [self.view addSubview:bgView];
    
    _imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
    [_imageView setBackgroundColor:[UIColor clearColor]];
    _imageView.contentMode = UIViewContentModeScaleAspectFit;
    [bgView addSubview:_imageView];
}

- (void)loadCodeUrl
{
    //二维码URL   http://211.65.216.54/getCheckUrl.action?caseTypeId=1&fkUserId=2&accountId=4
    //caseTypeId 1表示进场，2表示离场，fkUserId 是第三方账户ID
    
    NSString* refer = @"/getCheckUrl.action?";
    NSString* prefix = kASHttpUrl(refer);
    NSString* totalUrl = [NSString stringWithFormat:@"%@caseTypeId=%@&accountId=%@", prefix, @(_codeType), _pracUnitId];
    
    WEAKSELF
    [SVProgressHUD showWithStatus:@"加载中" maskType:SVProgressHUDMaskTypeClear];
    ASNetworkEngine *networkingEngine = [ASNetworkEngine sharedInstance];
    [networkingEngine GET:totalUrl parameters:nil success:^(id responseObject) {
        NSDictionary* jsonRsp = (NSDictionary *)responseObject;
        jsonRsp = [jsonRsp processDictionaryIsNSNull:jsonRsp];
        
        if (isSuccessRsp(jsonRsp))
        {
            NSString* url = [jsonRsp objectForKey:kASJsonUrl];
            [SVProgressHUD dismiss];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                [weakSelf generateQRCode:url];
            });
        }
        else
        {
            [SVProgressHUD showErrorWithStatus:errorMsgRsp(jsonRsp)];
        }
        
    } failure:^(NSError *error) {
        
        [SVProgressHUD showErrorWithStatus:@"网络异常，请稍后再试"];
    }];
}

- (void)generateQRCode:(NSString *)url
{
    CGFloat scale = [UIScreen mainScreen].scale;
    CGRect rect = CGRectMake(0, 0, 177, 177);
    CGFloat size = CGRectGetWidth(rect) * scale;
    
    UIImage *image = [self createNonInterpolatedUIImageFormCIImage:[self generateQRCodeFilter:url]
                                                          withSize:size];
    
    if (image)
    {
        _imageView.image = image;
    }
}

- (CIImage *)generateQRCodeFilter:(NSString *)url
{
    if ([url length] <= 0)
    {
        return nil;
    }
    
    CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
    [filter setDefaults];
    NSData *data = [url dataUsingEncoding:NSUTF8StringEncoding];
    [filter setValue:data forKey:@"inputMessage"];              //通过kvo方式给一个字符串，生成二维码
    [filter setValue:@"H" forKey:@"inputCorrectionLevel"];      //设置二维码的纠错水平，越高纠错水平越高，可以污损的范围越大
    
    //设置背景颜色和填充颜色 默认白色背景黑色填充
    CIColor *color1 = [CIColor colorWithCGColor:[UIColor blackColor].CGColor];
    CIColor *color2 = [CIColor colorWithCGColor:[UIColor whiteColor].CGColor];
    NSDictionary *parameters = [NSDictionary dictionaryWithObjectsAndKeys:
                                filter.outputImage,@"inputImage",
                                color1,@"inputColor0",
                                color2,@"inputColor1",nil];
    CIFilter *newFilter = [CIFilter filterWithName:@"CIFalseColor" withInputParameters:parameters];
    
    return [newFilter outputImage];//拿到二维码图片
}

// 对生成的二维码进行加工，使其更清晰
- (UIImage *)createNonInterpolatedUIImageFormCIImage:(CIImage *)image withSize:(CGFloat)size
{
    CGRect extent = CGRectIntegral(image.extent);
    CGFloat scale = MIN(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent));
    
    // 1.创建bitmap;
    size_t width = CGRectGetWidth(extent) * scale;
    size_t height = CGRectGetHeight(extent) * scale;
    
    //创建一个DeviceRGB颜色空间
    CGColorSpaceRef cs = CGColorSpaceCreateDeviceRGB();
    //CGBitmapContextCreate(void * _Nullable data, size_t width, size_t height, size_t bitsPerComponent, size_t bytesPerRow, CGColorSpaceRef  _Nullable space, uint32_t bitmapInfo)
    //width：图片宽度像素
    //height：图片高度像素
    //bitsPerComponent：每个颜色的比特值，例如在rgba-32模式下为8
    //bitmapInfo：指定的位图应该包含一个alpha通道。
    
    CGContextRef bitmapRef = CGBitmapContextCreate(nil, width, height, 8, 0, cs, (CGBitmapInfo)kCGImageAlphaPremultipliedLast);
    CIContext *context = [CIContext contextWithOptions:nil];
    //创建CoreGraphics image
    CGImageRef bitmapImage = [context createCGImage:image fromRect:extent];
    
    CGContextSetInterpolationQuality(bitmapRef, kCGInterpolationNone);
    CGContextScaleCTM(bitmapRef, scale, scale);
    CGContextDrawImage(bitmapRef, extent, bitmapImage);
    
    // 2.保存bitmap到图片
    CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);
    CGContextRelease(bitmapRef);
    CGImageRelease(bitmapImage);
    
    //原图
    UIImage *outputImage = [UIImage imageWithCGImage:scaledImage];
    return outputImage;
}

@end



